#!/bin/bash

# 一键配置MySQL的从服务器

# 获取eno1的网关
shost=$(ip a s | grep \/24 | awk '{print $2}' | awk -F'/' '{print $1}')
# 获取wlp2s0的网关
# shost=$(ifconfig eno1 | grep "inet" | awk '{print $2}' | awk -F':' '{print $2}')
# shost=$(ip a s | grep \/24 | awk '{print $2}' | awk -F'/' '{print $1}')
# 获取wlp2s0的网关
shost=$(ifconfig wlp2s0 | grep 'inet ' | awk '{print $2}')
sport=3307
data_dir=/mysql
slave="mysql-slave"

master="mysql-master"
# mhost='3.3.3.108'
mhost=$shost
mport=3306
user="replica"
passwd=1234

config_slave () {
    bin_log=$(rds master -n $master status | grep "mysql-bin" | awk -F'|' '{print $2}' | sed -e 's/^[ \t]*//g' -e 's/[ \t]*$//g')
    bin_pos=$(rds master -n $master status | grep "mysql-bin" | awk -F'|' '{print $3}' | sed -e 's/^[ \t]*//g' -e 's/[ \t]*$//g')
    rds master -n $master -h $mhost -P $mport grant $user $passwd
    rds slave stop
    rds slave connect -s "$user:$passwd:$mhost:$mport:$bin_log:$bin_pos"
    rds slave start
    rds slave status
}

destory() {
    docker rm -f $master $slave
    sudo rm $data_dir/data-master -rf
    sudo rm $data_dir/data-slave -rf
}

create() {
    rds master create -n $master -d $data_dir/data-master -c $data_dir/master.cnf -P $mport
    rds slave create -n $slave -d $data_dir/data-slave -c $data_dir/slave.cnf -P $sport
}

run() {
    create
    echo "这个过程大概需要1min,请耐心等待..."
    sleep 65
    config_slave
}

destory
run

